梦入琼楼寒有月,行过石树冻无烟

Python MySQL

Python MySQL

pymysql.err.OperationalError: (1045, “Access denied for user ‘root@localhost‘@’localhost’ (using password: YES)”)

​ 遇到此问题需要在终端界面中MySQL交互式模式中输入以下命令解决此问题。

1
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'New Password';

PyMySQL

1
pip3 install PyMySQL

​ 安装PyMySQL,可以在终端或者IDE集成开发环境中进行安装,之后就可以在开发环境中进行导入。

连接数据库例子

1
2
3
4
5
6
temysql = pymysql.connect(host='localhost',
port=3306 ,
user='root',
passwd='toor',
db='mysql',
charset='utf8')

游标

1
2
# 创建游标对象 cursor
cursor = temysql.cursor()

数据库操作

1
2
3
4
5
6
# MySQL 命令
cursor.execute('show databases;')
data = cursor.fetchone()

#输出
print('%s' % data)

关闭数据库和游标

1
2
3
4
5
# 关闭游标
cursor.close()

# 关闭数据库
temysql.close()

预处理语句

1
2
3
4
5
6
7
8
9
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
data = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT, SEX CHAR(1),
INCOME FLOAT )"""

#输出
print('%s' % data)

提交数据 or 回滚

1
2
3
4
5
6
7
8
9
10
try:
# 执行语句
cursor.execute(data)

# 提交数据
temysql.commit()

except:
# 数据回滚
temysql.rollback()

连接池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import time
import pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection

Pool = PooledDB(creator=pymysql, # 使用模块
maxconnections=6, # 连接池允许的最大连接数, 0 or None表示不限制
mincached=2, # 在初始化时的连接池最大连接数
maxcached=5, # 最多限制链接,0 or None表示无限制
maxshared=3, # 连接池最多的共享链接数量,0 or None表示无限制 (无论设置多少,_maxshared永远的为0,所以都是共享的)
blocking=True, # 连接池如果没有可用的连接诶是否阻塞等待。(True 等待 False不等待)
maxusage=None, # 连接可重复次数(None = 无限制)
setsession=[], # 开始回话前执行的命令列表
ping=0, # 检查服务是否可用 (0 = 永不停止,1 = 每当请求时,2 = 创建游标时, 4 = 执行查询时,7 = 始终)
host='localhost', # MySQL地址
port=3306, # MySQL Port
user='root', # MySQL User
passwd='toor', # MySQL Password
db='mysql', # MySQL db
charset='utf8') # MySQL 字符集
⬅️ Go back